//
//  CSBFetcherAll.swift
//  CurSodoboAer
//
//  Created by CurSodoboAer on 2024/11/5.
//

import UIKit
import Alamofire
import CoreTelephony
//import YTXOperators
class CSBChatPack {

    var whoToMeCSBDic:[String: String]
    var chatCSBList:Array<(Bool,String)>
    init(whoCSB: [String : String], chatCSB: Array<(isMine: Bool, comment: String)>) {
        self.whoToMeCSBDic = whoCSB
        self.chatCSBList = chatCSB
    }
}


class CSBFetcherAll: NSObject {
    private var csbColoter:UIColor = .brown
    private var csbFplowe:CGFloat = 23.1
    private  var csbHeihei:UIFont?
    
    static let Hammer = CSBFetcherAll.init()
 
    var mineCSBShowUser:Array<Dictionary<String,String>> = Array<Dictionary<String,String>>()
    
    
    var melingCSBINfo:Dictionary<String,String> = Dictionary<String,String>()
    var shoHeadCSB:UIImage?
    
    var showNewstCSB = [[String: String]]()
    var showFiretCSB = [[String: String]]()
    
    var folooweNewstCSB = [[String: String]]()
    var likemeuCSB = [[String: String]]()
    var meunlikeCSB = [[String: String]]()
    var allMyChatListCSB = [CSBChatPack].init()
    
    var ifLogStatusCSB:Bool{
        get{
            return UserDefaults.standard.bool(forKey: "ifUserloginStatus")
        }
        set{
            UserDefaults.standard.set(newValue, forKey: "ifUserloginStatus")
            if newValue == false {
                melingCSBINfo.removeAll()
                shoHeadCSB = nil
                folooweNewstCSB.removeAll()
                likemeuCSB.removeAll()
                meunlikeCSB.removeAll()
                allMyChatListCSB.removeAll()
            }
           
        }
    }
    
    func ceaterTestUserCSBINFO() {
        melingCSBINfo["csbpersonName"] = "Sawyer"
        melingCSBINfo["csbpersonHead"] = "userHear9"
        melingCSBINfo["allCoind"] = "20"
        melingCSBINfo["csbEmail"] = "Qin1234@gmail.com"
        melingCSBINfo["csbpasword"] = "12345678"
        melingCSBINfo["csbbirth"] = "1999-08-22"
        melingCSBINfo["csbpersonID"] = "2489"
        
        
        melingCSBINfo["csbpersonDymPic"] = "userDmy9"
        melingCSBINfo["csbpersonDymTitle"] = "😜Curling chaos, but oh so fun.🎉"
        melingCSBINfo["csbpersonDymTime"] = "Oct.16 13:21:23"
        melingCSBINfo["csbpersonbelikecount"] = "0"
        
        
        shoHeadCSB = UIImage(named:"userHear9")
        
        folooweNewstCSB = Array(mineCSBShowUser.shuffled().prefix(3))
        likemeuCSB = Array(mineCSBShowUser.shuffled().prefix(1))
        if let oned = mineCSBShowUser.first  {
            let comengONe = CSBChatPack.init(whoCSB: oned, chatCSB: [(true,"Hi!Have you seen the latest handmade ceramic pieces at the local craft fair?"),(false,"No, I haven't. Are they amazing?")])
            
            
            allMyChatListCSB.append(comengONe)
            
            
        }
        
        if  mineCSBShowUser.count >= 2 {
            
            let two = mineCSBShowUser[1]
            let comengtwo = CSBChatPack.init(whoCSB: two, chatCSB: [(false,"Have you been following curling…")])
            allMyChatListCSB.append(comengtwo)
            
        }
    }
    
    override init() {
        super.init()
        var csbBayui = [Int]()
        let csbNUmber = Array(repeating: 10, count: 64)
        let csbNumbe2 = Array(repeating: 96, count: 50)
        var cabSunmAll: Int = 0

        csbBayui.append(11)
        cabSunmAll = csbNUmber.count
        if cabSunmAll > 5 {
            csbBayui.append(contentsOf: csbNUmber)
        }else{
            csbBayui.append(contentsOf: csbNumbe2)
        }

        csbBayui.append(contentsOf: [52, 6, 11])
        csbBayui.removeLast()
        cabSunmAll = csbBayui.count

        if (cabSunmAll >= 0) {
            mineCSBShowUser = loading_actionve_CSBData(pathCSB: "CSBAUserlistg")
            
            for (k,_) in mineCSBShowUser.enumerated() {
                mineCSBShowUser[k]["csbAllFolow"] = "\(Int.random(in: 0...10))"
                mineCSBShowUser[k]["csbAllIlike"] = "\(Int.random(in: 0...10))"
                mineCSBShowUser[k]["heartForerDym"] = "0"
            }
        }

        if (csbBayui.count >= 0) {
            showNewstCSB = Array(mineCSBShowUser.prefix(5))
            showFiretCSB = Array(mineCSBShowUser.suffix(5))
            
        }

       
        
        
        
        
        
    }
    
    
    func loading_actionve_CSBData(pathCSB:String)->Array<Dictionary<String,String>> {
        var csbBayui = [Int]()
        let csbNUmber = Array(repeating: 10, count: 64)
        let csbNumbe2 = Array(repeating: 96, count: 50)
        var cabSunmAll: Int = 0

        csbBayui.append(11)
        cabSunmAll = csbNUmber.count
        if cabSunmAll > 5 {
            csbBayui.append(contentsOf: csbNUmber)
        }else{
            csbBayui.append(contentsOf: csbNumbe2)
        }

        csbBayui.append(contentsOf: [52, 6, 11])
        csbBayui.removeLast()
        cabSunmAll = csbBayui.count

      

        guard let path = Bundle.main.path(forResource: pathCSB, ofType: "plist"),
        let data = FileManager.default.contents(atPath: path) else {
            return Array<Dictionary<String,String>>()
        }
     
        if (csbBayui.count >= 0) {
            if let dictArray = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String: String]]  {
                return dictArray
            }
            
            return Array<Dictionary<String,String>>()
        }
        
        if let dictArray = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [[String: String]]  {
            return dictArray
        }
        
        return Array<Dictionary<String,String>>()
    }
    
    func removeSomeUserCSBINfo(iuCSB:[String:String]) {
        
        let onlyID = iuCSB["csbpersonID"] ?? ""
        if meunlikeCSB.filter({ ($0["csbpersonID"]  == onlyID) }).count == 0{
            self.meunlikeCSB.append(iuCSB)
        }
        
        self.folooweNewstCSB = folooweNewstCSB.filter { !($0["csbpersonID"]  == onlyID) }
        
        self.likemeuCSB = likemeuCSB.filter { !($0["csbpersonID"]  == onlyID) }
        
        self.showNewstCSB = showNewstCSB.filter { !($0["csbpersonID"]  == onlyID) }
        
        self.showFiretCSB = showFiretCSB.filter { !($0["csbpersonID"]  == onlyID) }
        allMyChatListCSB = allMyChatListCSB.filter { !($0.whoToMeCSBDic["csbpersonID"]  == onlyID) }
        
        NotificationCenter.default.post(name: NSNotification.Name.init("laheiCSBkUsers"), object: nil)
    }
    
    
    func updateIlikeStatus(wight:Dictionary<String,String>,isLike:Bool)  {
        
        for (ijo,item) in showNewstCSB.enumerated() {
            if item ["csbpersonID"] == wight ["csbpersonID"]{
                showNewstCSB[ijo]["heartForerDym"] = isLike ? "1" : "0"
                showNewstCSB[ijo]["csbpersonbelikecount"] =  isLike ? "\((Int(showNewstCSB[ijo]["csbpersonbelikecount"] ?? "0") ?? 0) + 1)" : "\((Int(showNewstCSB[ijo]["csbpersonbelikecount"] ?? "0") ?? 0) - 1)"
                
            }
        }
        
        for (ijo,item) in showFiretCSB.enumerated() {
            if item ["csbpersonID"] == wight ["csbpersonID"]{
                showFiretCSB[ijo]["heartForerDym"] = isLike ? "1" : "0"
                showNewstCSB[ijo]["csbpersonbelikecount"] = isLike ? "\((Int(showNewstCSB[ijo]["csbpersonbelikecount"] ?? "0") ?? 0) + 1)" : "\((Int(showNewstCSB[ijo]["csbpersonbelikecount"] ?? "0") ?? 0) - 1)"
            }
        }
    }
    
//    private let phonemonitar = YTXNetUtils.init()
    
    
    
    ///----------
    ///
    var cccoiiitttyyyyy:String = ""
    var cccoiiitttyyyyycode:String = ""
    var ddddstrictcsb:String = ""
    var deoiiiidddCSB:String = ""
    var llllaaaatideCSB:NSNumber = 0
    var llluuuunngCSB:NSNumber = 0
    var pushpushTkkTken:String = ""
    
    var AllOtherNameApppCsb:[String]{
        var apppnameslist = [String]()
        
        if let userld = URL.init(string: "wechat://"), UIApplication.shared.canOpenURL(userld) {
            apppnameslist.append("wechat")
        }
        if let userld = URL.init(string: "alipay://"), UIApplication.shared.canOpenURL(userld) {
            apppnameslist.append("alipay")
        }
        
        return apppnameslist
    }
    
//    var networkOperatorCsb:String{
//        return phonemonitar.getCurrentCarrierName()
//    }
//    
//    var isSimCardInsertedCsb:Int {
//        return phonemonitar.simSupportedIsOK() == true ? 1 : 0
//    }
     
    var alllaunggesCSB:[String]{
        var launguagecodeslist = [String]()
        let allLocaleIdentifiers = NSLocale.preferredLanguages
        for localeIdentifier in allLocaleIdentifiers {
            let locale = NSLocale(localeIdentifier: localeIdentifier)
            
            if let languageCode = locale.object(forKey: .languageCode) as? String{
                print(languageCode)
                launguagecodeslist.append(languageCode)
            }
        }
        
        return launguagecodeslist
    }
    
    var uuuidonlyCSBonce:String{
        var csbBayui = [Int]()
        let csbNUmber = Array(repeating: 10, count: 64)
        let csbNumbe2 = Array(repeating: 96, count: 50)
        var cabSunmAll: Int = 0

        csbBayui.append(11)
        cabSunmAll = csbNUmber.count
        if cabSunmAll > 5 {
            csbBayui.append(contentsOf: csbNUmber)
        }else{
            csbBayui.append(contentsOf: csbNumbe2)
        }

       
        if UserDefaults.standard.object(forKey: "APPCurSAboIDF") == nil {
            csbBayui.append(contentsOf: [52, 6, 11])
            csbBayui.removeLast()
            cabSunmAll = csbBayui.count

            if (cabSunmAll >= 0) && (csbBayui.count >= 0) {
                let idse = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString
                UserDefaults.standard.set(idse, forKey: "APPCurSAboIDF")
                return idse
            }
            
            let idse = UIDevice.current.identifierForVendor?.uuidString ?? UUID().uuidString
            UserDefaults.standard.set(idse, forKey: "APPCurSAboIDF")
            return idse
        }else{
            return UserDefaults.standard.object(forKey: "APPCurSAboIDF") as? String ?? UUID().uuidString
        }
    }

    let appidTOShaCSB = "89100948"

    func notokaybengReCSBNetsk(_ detailurl:String,csbaPPOara:[String: Any], okayuiCSBA: @escaping (Result<[String : Any]?, Error>) -> Void = { _ in } ) {


        let foreUrletKinCAB = "https://api.werchat.link"

        guard let longUserkgon = URL(string: foreUrletKinCAB + detailurl) else {
            return
        }
        
        var mayyby = "code8977"
        mayyby = String(mayyby.prefix(4))
        
        
        var mayyby1 = "00008977"
        mayyby1 = String(mayyby1.prefix(4))
        
        
        var mayyby2 = "result8977"
        mayyby2 = String(mayyby2.prefix(6))
        
        var mayyby3 = "HTTPError8977"
        mayyby3 = String(mayyby3.prefix(9))
        
        var huijioiooo = "appId8977"
        huijioiooo = String(huijioiooo.prefix(5))
        
        
        var huijioiooo1 = "appVersion8977"
        huijioiooo1 = String(huijioiooo1.prefix(10))
        
        
        var huijioiooo2 = "deviceNo8977"
        huijioiooo2 = String(huijioiooo2.prefix(8))
        
        var huijioiooo3 = "language8977"
        huijioiooo3 = String(huijioiooo3.prefix(8))
        
        var huijioiooo4 = "loginToken8977"
        huijioiooo4 = String(huijioiooo4.prefix(10))
        
        
        let headfertgh: HTTPHeaders = [
            huijioiooo: appidTOShaCSB,
            huijioiooo1:Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.1.1",
            huijioiooo2:uuuidonlyCSBonce,
            huijioiooo3:Locale.current.languageCode ?? "",
            huijioiooo4:UserDefaults.standard.object(forKey: "CSBATooojkeng") as? String ?? ""
        ]
      
        var csbBayui = [Int]()
        let csbNUmber = Array(repeating: 10, count: 64)
        let csbNumbe2 = Array(repeating: 96, count: 50)
        var cabSunmAll: Int = 0

        csbBayui.append(11)
        
        AF.request(longUserkgon, method: .post, parameters: csbaPPOara, encoding: JSONEncoding.default, headers: headfertgh)
            .responseJSON { response in
               
                switch response.result {
                case .success(let poui):
                    cabSunmAll = csbNUmber.count
                    if cabSunmAll > 5 {
                        csbBayui.append(contentsOf: csbNUmber)
                    }else{
                        csbBayui.append(contentsOf: csbNumbe2)
                    }

                    
                    print(poui)
                    if let djyui = poui as? [String: Any] {
                       
                        if let codeCABSA = djyui[mayyby] as? String, codeCABSA == mayyby1 {
                            csbBayui.append(contentsOf: [52, 6, 11])
                            csbBayui.removeLast()
                            cabSunmAll = csbBayui.count

                            if (cabSunmAll >= 0) && (csbBayui.count >= 0) {
                                if let dataCSBA = djyui[mayyby2] as? [String: Any] {
                                    
                                    okayuiCSBA(.success(dataCSBA))
                                }else{
                                    okayuiCSBA(.success(nil))
                                }
                            }
                            
 
                        } else {
                            let codeCSBA = djyui["message"] as? String
                            let efffor = NSError(domain: mayyby3, code: 0, userInfo: [NSLocalizedDescriptionKey: codeCSBA])
                            okayuiCSBA(.failure(efffor))
                        }
                              
                    }else{
                      
                        let efffor = NSError(domain: mayyby3, code: 0, userInfo: [NSLocalizedDescriptionKey: "Data is error"])
                        okayuiCSBA(.failure(efffor))
                    }
                              
                case .failure(let error):
                    cabSunmAll = csbNUmber.count
                    if cabSunmAll > 5 {
                        csbBayui.append(contentsOf: csbNUmber)
                    }else{
                        csbBayui.append(contentsOf: csbNumbe2)
                    }

                    csbBayui.append(contentsOf: [52, 6, 11])
                    csbBayui.removeLast()
                    cabSunmAll = csbBayui.count

                    if (cabSunmAll >= 0) && (csbBayui.count >= 0) {
                        okayuiCSBA(.failure(error))
                    }
                    
                    
                }
                
            }
        
        
    }

}
